///////////////////////////////////////////////////////////////////////
//  CS 3716 (Winter 2012), Assignment #4                       		 //
//  Program File Name: MasterRecDatabase.java                  		 //
//       Student Name: Jonathan Hart-Wall, Adam Murphy         		 //
//					   Yifu Liang, Joshua Dowling			   		 //
//         Login Name: jcwhw1, agm264 , n96yl, n23jdd                //
//              MUN #: 200933455, 200933133, 200565679, 200703684    //
///////////////////////////////////////////////////////////////////////

import java.io.*;
import java.util.ArrayList;
/**
 * This class handles the individual classes
 */
public class MasterRecDatabase 
{

	private File masterRecDatabaseDir;
	private ArrayList<RecDatabase> recDatabase;
	/**
	 * Constructor
	 * @param fileLocation File The pathname of the text file
	 */
	public MasterRecDatabase(String fileLocation)
	{
		masterRecDatabaseDir = new File(fileLocation);
		recDatabase = new ArrayList<RecDatabase>();
	}
	
	/**
	 * Gets the recDatabase.
	 * @return an ArrayList<RecDatabase> list.
	 */
	public ArrayList<RecDatabase> getRecDatabases()
	{
		return recDatabase;
	}
	
	/**
	 * Adds/creates a recDatabase to the MasterRecDatabase list.
	 * @param name the name of the recdatabase being added.
	 */
	public void addRecDatabase(String name)
	{
		recDatabase.add(new RecDatabase(name));
	}
		
	/**
	 * Returns a specific  RecDatabase
	 * @param name name of desired database
	 * @return recDatabase with name that equals @param name
	 * @throws NoSuchListException
	 */
	public RecDatabase getRecDatabase(String name) throws NoSuchListException
	{
		for (RecDatabase recDb : recDatabase)
		{
			if (recDb.getName().equals(name))
				return recDb;
		}
		throw new NoSuchListException();
	}
	/**
	 * Loads all databases.
	 * @throws IOException
	 */
	public void load() throws IOException
	{
		if (!masterRecDatabaseDir.exists())
		{
			masterRecDatabaseDir.mkdir();
			return;
		}
		
		File[] recDatabaseFiles = masterRecDatabaseDir.listFiles();
		
		for (File recDatabaseFile : recDatabaseFiles)
		{
			BufferedReader br = new BufferedReader(new FileReader(recDatabaseFile));
		
			String listName = br.readLine();
			String line = br.readLine();
			
			ArrayList<MovieRec> movieRecs = new ArrayList<MovieRec>();
			while (!(line = br.readLine()).trim().equals(""))
			{
				String[] movieRecParams = line.split("#");
				movieRecs.add(new MovieRec(movieRecParams[0], Double.parseDouble(movieRecParams[3]), Integer.parseInt(movieRecParams[1]), movieRecParams[2], movieRecParams[4]));
			}
			
			ArrayList<String> history = new ArrayList<String>();
			while ((line = br.readLine()) != null)
				history.add(line.trim());
			
			recDatabase.add(new RecDatabase(listName, movieRecs, history));	
			br.close();
		}
	}
	
}
